import 'package:dio/dio.dart';
import 'package:short_drama/utils/global_util.dart';
import 'dart:convert';
import 'dart:io';

class HttpUtil {
  static final HttpUtil _instance = HttpUtil._internal();
  late Dio _dio;

  factory HttpUtil() => _instance;

  HttpUtil._internal() {
    _dio = Dio(
      BaseOptions(
        baseUrl: "https://hailiyu.37yule.cn/api/",
        connectTimeout: const Duration(seconds: 60),
        receiveTimeout: const Duration(seconds: 60),
        contentType: "application/json",
      ),
    );

    _dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (options, handler) {
          return handler.next(options);
        },
        onResponse: (response, handler) {
          return handler.next(response);
        },
        onError: (DioException e, handler) {
          return handler.next(e);
        },
      ),
    );
  }

  void setHeaders(Map<String, dynamic> headers) {
    _dio.options.headers.addAll(headers);
  }

  Future<Response> put(
    String path, {
    Map<String, dynamic>? params,
    Options? options,
  }) async {
    try {
      setHeaders({'token': GlobalUtil.userToken});
      final response = await _dio.put(
        path,
        queryParameters: params,
        options: options,
      );
      return response;
    } on DioException catch (e) {
      _handleError(e);
      rethrow;
    }
  }

  Future<Response> get(
    String path, {
    Map<String, dynamic>? params,
    Options? options,
  }) async {
    try {
      setHeaders({'token': GlobalUtil.userToken});
      final response = await _dio.get(
        path,
        queryParameters: params,
        options: options,
      );
      return response;
    } on DioException catch (e) {
      _handleError(e);
      rethrow;
    }
  }

  Future<Response> post(
    String path, {
    Map<String, dynamic>? params,
    dynamic data,
    Options? options,
  }) async {
    try {
      setHeaders({'token': GlobalUtil.userToken});
      final response = await _dio.post(
        path,
        data: data,
        queryParameters: params,
        options: options,
      );
      return response;
    } on DioException catch (e) {
      _handleError(e);
      rethrow;
    }
  }

  Future<Response> upload(
    String path, {
    required String filePath,
    String? fileName,
    File? file,
    Map<String, dynamic>? formData,
    ProgressCallback? progress,
  }) async {
    try {
      String base64WithPrefix = await imageToBase64(file!);
      FormData formData = FormData.fromMap({'content': base64WithPrefix});
      try {
        final response = await _dio.post(
          'file/image/base64',
          data: formData,
          options: Options(contentType: Headers.jsonContentType),
          onSendProgress: progress,
        );
        return response;
      } catch (e) {
        throw Exception('上传失败: ${e}');
      }
    } on DioException catch (e) {
      _handleError(e);
      rethrow;
    }
  }

  Future<String> imageToBase64(File file) async {
    File newFile = File(file.path);
    List<int> imageBytes = await newFile.readAsBytes();
    String base64String = base64Encode(imageBytes);
    //return 'data:image/png;base64,$base64String';
    return base64String;
  }

  String _handleError(DioException e) {
    String errorMessage = "网络请求失败";
    if (e.response != null) {
      errorMessage = '服务器异常：${e.response?.statusCode}';
    } else if (e.type == DioExceptionType.connectionTimeout) {
      errorMessage = '连接超时';
    } else if (e.type == DioExceptionType.unknown) {
      errorMessage = '网络不可用';
    }
    return errorMessage;
  }
}
